package smlab.manager
{
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.utils.Dictionary;
	
	/**
	 * 声音管理类
	 * @author simon
	 * xx
	 */
	public class SoundManager_SM
	{
		private var m_sounds:Dictionary;
		private var m_channels:Dictionary;
		private var m_musicChannel:SoundChannel;
		private var m_musicTransform:SoundTransform;
		private var m_soundTransform:SoundTransform;
		private static var _instance:SoundManager_SM;
		
		
		public static function get instance():SoundManager_SM
		{
			if(_instance == null)
			{
				_instance = new SoundManager_SM();
			}
			return _instance;
		}
		
		public function get soundVolume():Number{ return m_soundTransform.volume; }
		public function set soundVolume( volume:Number ) : void
		{ 
			if( volume < 0 )
			{
				volume = 0;
			}
			m_soundTransform.volume = volume; 
		}
		public function get musicVolume():Number{ return m_musicTransform.volume; }
		public function set musicVolume( volume:Number ) : void
		{
			if( volume < 0 )
			{
				volume = 0;
			}
			m_musicTransform.volume = volume;
			m_musicChannel.soundTransform = m_musicTransform;
		}
		
		public function SoundManager_SM()
		{
			m_musicChannel = new SoundChannel();
			m_musicTransform = new SoundTransform( 1 );
			m_soundTransform = new SoundTransform( 1 );
			m_sounds = new Dictionary();
			m_channels = new Dictionary();
		}
		
		public function registerSound( sound:Sound, id:String ) : void
		{
			m_sounds[ id ] = sound;
		}
		
		public function playSound( id:String, startTime:int = 0, loops:int = 0 ) : void
		{			
			if( m_sounds[ id ] == null )
			{
				throw new Error( "<SoundManager_SM> Sound: " + id + " does not exist!" );		
			}
			else
			{
				m_channels[ id ] = m_sounds[ id ].play( startTime, loops, m_soundTransform );
			}
		}
		
		public function stopSound( id:Sound ) : void
		{
			if( m_channels[ id ] != null )
			{
				m_channels[ id ].stop();
				delete m_channels[ id ];
			}
		}
		
		public function playMusic( id:String, start:int = 0, loops:int=0 ) : void
		{
			if( m_sounds[ id ] == null )
			{
				throw new Error( "<SoundManager_SM> Sound: " + id + " does not exist!" );		
			}
			m_musicChannel = m_sounds[ id ].play( start, loops, m_musicTransform );
		}
		
		public function stopMusic() : void
		{
			m_musicChannel.stop();
		}
	}
}
/*
使用实例：

[Embed(source="../assets/1.mp3")]
var GunshotSound:Class;
[Embed(source="../assets/2.mp3")]
var MarioSound:Class;

SoundManager_SM.instance.registerSound( new GunshotSound(), "sound0" );
SoundManager_SM.instance.registerSound( new MarioSound(), "music" );

SoundManager_SM.instance.playSound( "sound" + rand );
SoundManager_SM.instance.playMusic( "music" );
*/